package com.zmzncs.lmtc.module.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.zmzncs.lmtc.common.config.ClientConfig;
import com.zmzncs.lmtc.common.pojo.tengda.CurrFeeForm;
import com.zmzncs.lmtc.common.pojo.tengda.TengdaForm;
import com.zmzncs.lmtc.module.order.service.OrderInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import static com.zmzncs.lmtc.module.order.service.impl.OrderInfoServiceImpl.tengdaOrderFormList;

@RestController
@RequestMapping("/order")
@Api(tags = {"订单"})
public class OrderController {

    @Autowired
    private ClientConfig clientConfig;
    @Autowired
    private OrderInfoService orderInfoService;

    @ApiOperation(value = "测试-推送消息")
    @PostMapping(value = "/push")
    public void push(@Param("topic") String topic, @Param("message") String message) {

        clientConfig.publish(topic, null, message);
    }

    @ApiOperation(value = "实时订单")
    @GetMapping(value = "/queryCurrOrder")
    public TengdaForm queryCurrOrder(@RequestParam String bolianParkId, @RequestParam String carNumber) throws InterruptedException {
        String uuid = UUID.randomUUID().toString();

        JSONObject publishJson = new JSONObject();
        publishJson.put("payScene", 0);
        publishJson.put("plateNumber", carNumber);
        List<Object> dataItems = new ArrayList<>();
        dataItems.add(publishJson);

        JSONObject resJson = new JSONObject();
        resJson.put("code", 1);
        resJson.put("parkCode", bolianParkId);
        resJson.put("serviceId", "pay.queryfeebyplate");
        resJson.put("uuid", uuid);
        resJson.put("dataItems", dataItems);

        clientConfig.publish("tcp/" + bolianParkId, "pay.queryfeebyplate", resJson.toString());

        //  缓存中查询响应数据
        for (int i=0; i<10; i++) {
            Thread.sleep(500);

            //  如果uuid相同，则响应数据
            Optional<TengdaForm> first = tengdaOrderFormList.stream().filter(tengdaForm -> tengdaForm.getUuid().equals(uuid)).findFirst();
            if(first.isPresent()){
                //  删除缓存
                orderInfoService.deleteCache(first.get());
                return first.get();
            }
        }

        TengdaForm tengdaForm = new TengdaForm();
        tengdaForm.setCode(0);
        tengdaForm.setParkCode(bolianParkId);
        tengdaForm.setServiceId("pay.queryfeebyplate");
        tengdaForm.setUuid(uuid);

        return tengdaForm;
    }

}